import { _decorator, Component } from "cc";
import EventMgr from "./EventMgr";

const { ccclass, property,menu } = _decorator;

@ccclass
@menu("use/计时器")
export default class RunTimer extends Component {

    runTime: number = -1;
    currTime: number = 0;
    bar: number = 0;
    runing: boolean = false;

    _intervalId: number = 0;

    // LIFE-CYCLE CALLBACKS:

    startTimer(_time: number = -1) {
        if (this.runing) return;
        this.runing = true;

        console.log("设置游戏时间：" ,_time);

        this.runTime = _time;

        this._intervalId = setInterval(() => this.func(), 10);
    }

    func() {
        this.currTime += 0.01;
        // console.log(" * " + this.currTime);
        EventMgr.Inst.emit("time run", this.currTime);

        if (this.runTime > 0) {
            if (this.currTime >= this.runTime) {
                this.currTime = this.runTime;
                this.end();
            }
        }
    }

    stopTime(){
        if (this.runing) this.runing = false;
        
        clearInterval(this._intervalId);
    }

    end() {
        if (this.runing) this.runing = false;

        clearInterval(this._intervalId);

        EventMgr.Inst.emit("time end", this.currTime);

        //this.getCurTime();

    }

    onDestroy() {
        this.end();
    }


    getCurTime(): string {
        const date = new Date();
        const str = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        console.log("时间：" + str);
        return str;
    }

}
